package band.wukong.practice.netty.userguide.objectecho;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.List;

/**
 * Desc: Handler implementation for the object echo client.
 *       It initiates the ping-pong traffic between the object echo client
 *       and server by sending the first message to the server.
 * author: wukonggg@139.com
 */
public class ObjectEchoClientHandler extends ChannelInboundHandlerAdapter {

    private static final Logger logger = LogManager.getLogger();

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws InterruptedException {
        // business
        // Send the first message if this handler is a client-side handler.
        ctx.writeAndFlush(new ObjectEcho().getFirstMessage());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws InterruptedException {
        // Echo back the received object to the server.
        ctx.write(msg);
        logger.debug(msg);
        ctx.channel().close().sync();
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws InterruptedException {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
